/* http://github.com/mindmup/bootstrap-wysiwyg */
/*global jQuery, $, FileReader*/
/*jslint browser:true*/
(function ($) {
    'use strict';
    var readFileIntoDataUrl = function (fileInfo) {
        var loader = $.Deferred(),
            fReader = new FileReader();
        fReader.onload = function (e) {
            loader.resolve(e.target.result);
        };
        fReader.onerror = loader.reject;
        fReader.onprogress = loader.notify;
        fReader.readAsDataURL(fileInfo);
        return loader.promise();
    };
    $.fn.cleanHtml = function () {
        var html = $(this).html();
        return html && html.replace(/(<br>|\s|<div><br><\/div>|&nbsp;)*$/, '');
    };
    
    $.fn.gethtml=function () {
        var editor = this.find('.editor-zone:first');
        return editor.html();
    }
    
    $.fn.wysiwyg = function (userOptions) {

        options = $.extend({}, $.fn.wysiwyg.defaults, userOptions);

        var editzone = document.createElement("div");
        $(editzone).addClass('editor-zone');
        var editor_box=this;
        var inithtml=editor_box.html();
        // inithtml="<p>"+inithtml+"</p>";
        editor_box.html('');
        editor_box.append(editzone);
        var editor = editor_box.find('.editor-zone:first');
        if(editor_box.hasClass('auto-fix'))
        {
            editor.addClass('eidtor-fix');
        }
        editor.html(inithtml);
        
        //兼容ie的insertHtml；
        var myfunc = {
            brtag:['blockquote'],
            //标签处理
            taghandle:function () {
                //删除span标签
                var spans=$(editzone).find('span');
                spans.each(function () {
                    $(this).replaceWith($(this).html());
                });
                return true;
            },

            insertHtml: function (str) {
                if ($.browser().browser.msie) {
                    document.selection.createRange().pasteHTML(str);
                } else {
                    execCommand('insertHtml', str);
                }
            },

            //enter keydown
            enterdown:function (data,e) {
                return true;
            },
            //enter keyup
            enterup:function () {
                return true;
            },
        initbar: function (options) {
                var editbar = $('<div class="btn-toolbar editor-toolbar" data-role="editor-toolbar" data-target="#editor"></div>');

                var editbar_btn = {
                    'bold': '<a class="btn btn-default" data-edit="bold" title="Bold (Ctrl/Cmd+B)"><i class="fa fa-bold"></i></a>',
                    'italic': '<a class="btn btn-default" data-edit="italic" title="Italic (Ctrl/Cmd+I)"><i class="fa fa-italic"></i></a>',
                    'strikethrough': '<a class="btn btn-default" data-edit="strikethrough" title="Strikethrough"><i class="fa fa-strikethrough"></i></a>',
                    'underline': '<a class="btn btn-default" data-edit="underline" title="Underline (Ctrl/Cmd+U)"><i class="fa fa-underline"></i></a>',
                    'ol': '<a class="btn btn-default" data-edit="insertunorderedlist" title="Bullet list"><i class="fa fa-list-ul"></i></a>',
                    'ul': '<a class="btn btn-default" data-edit="insertorderedlist" title="Number list"><i class="fa fa-list-ol"></i></a>',
                    'justifyleft': '<a class="btn btn-default" data-edit="justifyleft" title="Align Left (Ctrl/Cmd+L)"><i class="fa fa-align-left"></i></a>',
                    'justifycenter': '<a class="btn btn-default" data-edit="justifycenter" title="Center (Ctrl/Cmd+E)"><i class="fa fa-align-center"></i></a>',
                    'justifyright': '<a class="btn btn-default" data-edit="justifyright" title="Align Right (Ctrl/Cmd+R)"><i class="fa fa-align-right"></i></a>',
                    'justifyfull': '<a class="btn btn-default" data-edit="justifyfull" title="Justify (Ctrl/Cmd+J)"><i class="fa fa-align-justify"></i></a>',
                    //link
                    'link': '<a class="btn btn-default" data-edit="addlink" data-toggle="modal" data-target="#addLinkModal"  title="Hyperlink"><i class="fa fa-link"></i></a>' +
                    '<a class="btn btn-default" data-edit="unlink" title="Remove Hyperlink"><i class="fa fa-cut"></i></a>',
                    //linkmodel
                    "linkmodel":'<div class="modal fade" id="addLinkModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
                    '<div class="modal-dialog">' +
                    '<div class="modal-content">' +
                    '<div class="modal-header">' +
                    '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
                    '<h4 class="modal-title" id="myModalLabel">添加链接</h4>' +
                    '</div>' +
                    '<div class="modal-body">' +
                    '<div class="form-group">' +
                    '<label for="" class="control-label">链接(http://)：</label>' +
                    '<input class="span2 form-control add_link_link" placeholder="链接" type="text"/>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '<label for="" class="control-label">文字：</label>' +
                    '<input class="span2 form-control add_link_text" placeholder="文字" type="text"/>' +
                    '</div>' +
                    '</div>' +
                    '<div class="modal-footer">' +
                    '<button type="button" class="btn btn-primary add_link_btn" data-dismiss="modal">添加</button>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>',
                    //linkmodel
                    "imgsetmodel":'<div class="modal fade" id="imgSet" role="dialog" aria-labelledby="imgSet" aria-hidden="true">' +
                    '<div class="modal-dialog">' +
                    '<div class="modal-content">' +
                    '<div class="modal-header">' +
                    '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
                    '<h4 class="modal-title" id="myModalLabel">设置图片</h4>' +
                    '</div>' +
                    '<div class="modal-body">' +
                    '<div class="form-group">' +
                    '<label for="" class="control-label">图片宽度：</label>' +
                    '<input class="span2 form-control img_width" placeholder="图片宽度" type="text"/>' +
                    '</div>' +
                    // '<div class="form-group">' +
                    // '<label for="" class="control-label">文字：</label>' +
                    // '<input class="span2 form-control add_link_text" placeholder="文字" type="text"/>' +
                    // '</div>' +
                    '</div>' +
                    '<div class="modal-footer">' +
                    '<button type="button" class="btn btn-primary img_set_btn" data-dismiss="modal">设定</button>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>',
                    //insertpic
                    'insertpic': '' +
                    '<a class="btn btn-default _insert_img"  title="添加图片" id="pictureBtn">' +
                    '<i class="fa fa-file-picture-o"></i>' +
                    '</a>' +
                    '<input type="file" data-role="magic-overlay" data-target="#pictureBtn" style="display: none" data-edit="insertImage"/>',
                    'undo': '<a class="btn btn-default" data-edit="undo" title="Undo (Ctrl/Cmd+Z)"><i class="fa fa-undo"></i></a>',
                    'redo': '<a class="btn btn-default" data-edit="redo" title="Redo (Ctrl/Cmd+Y)"><i class="fa fa-repeat"></i></a>',
                    'fontsize': '' +
                    '<a class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Font Size">' +
                    '<i class="fa fa-text-height"></i>&nbsp;' +
                    '<b class="caret"></b></a>' +
                    '<ul class="dropdown-menu">' +
                    '<li><a data-edit="fontSize 5"><font size="5">Huge</font></a></li>' +
                    '<li><a data-edit="fontSize 3"><font size="3">Normal</font></a></li>' +
                    '<li><a data-edit="fontSize 1"><font size="1">Small</font></a></li>' +
                    '</ul>',
                    //设置标题
                    'title':'<a class=" btn btn-default dropdown-toggle" data-toggle="dropdown" title="小标">' +
                    '<i class="fa fa-header"></i>&nbsp; <b class="caret"></b>' +
                    '</a>' +
                    '<ul class="dropdown-menu">' +
                    '<li><a data-edit="_to h1"><h1>标题一</h1></a></li>' +
                    '<li><a data-edit="_to h2"><h2>标题二</h2></a></li>' +
                    '<li><a data-edit="_to h3"><h3>标题三</h3></a></li>' +
                    '<li><a data-edit="_to h4"><h4>标题四</h4></a></li>' +
                    '<li><a data-edit="_to div">正文</a></li>' +
                    '</ul>',
                    'hr':'<a class="btn btn-default" data-edit="hr" title="分隔线">--</a>',
                    'quote':'<a class="btn btn-default" data-edit="FormatBlock blockquote" title="分隔线"><i class="fa fa-quote-left"></i></a>',

                };


                for (var btn_name in options.editbar) {
                    if(options.editbar[btn_name]=='link')
                    {
                        var linkmodel=$(editbar_btn['linkmodel']);
                        editor_box.prepend(linkmodel);
                    }

                    if(options.editbar[btn_name]=='insertpic')
                    {
                        var linkmodel=$(editbar_btn['imgsetmodel']);
                        editor_box.prepend(linkmodel);
                    }

                    var btnobj = $("<div class='btn-group'>"+editbar_btn[options.editbar[btn_name]]+"</div>");
                    editbar.append(btnobj);

                }

                editor_box.prepend(editbar);
            },
        };
        

        // 将编辑器暴露出来的文字和图片，都用 p 来包裹
        var wrapImgAndText = function () {
            var $txt=$(editzone);
            var $imgs = $txt.children('img');
            var txt = $txt[0];
            var childNodes = txt.childNodes;
            var childrenLength = childNodes.length;
            var i, childNode, p;

            // 处理图片
            $imgs.length && $imgs.each(function () {
                $(this).wrap('<p>');
            });

            // 处理文字
            for (i = 0; i < childrenLength; i++) {
                childNode = childNodes[i];
                if (childNode.nodeType === 3 && childNode.textContent && $.trim(childNode.textContent)) {
                    $(childNode).wrap('<p>');
                }
            }
        };


        wrapImgAndText();

        // 清空内容为空的<p>，以及重复包裹的<p>（在windows下的chrome粘贴文字之后，会出现上述情况）
        var clearEmptyOrNestP = function () {
            var $txt = $(editzone);
            var $pList = $txt.find('p');

            $pList.each(function () {
                var $p = $(this);
                var $children = $p.children();
                var childrenLength = $children.length;
                var $firstChild;
                var content = $.trim($p.html());

                // 内容为空的p
                if (!content) {
                    $p.remove();
                    return;
                }

                // 嵌套的p
                if (childrenLength === 1) {
                    $firstChild = $children.first();
                    if ($firstChild.get(0) && $firstChild.get(0).nodeName === 'P') {
                        $p.html( $firstChild.html() );
                    }
                }
            });
        };

        //滚动浮动
        $(document).scroll(
            function () {
                var of = editor_box.offset();
                var baro=editor_box.find('.editor-toolbar:first');
                if (document.body.scrollTop > of.top) {
                    baro.css('position', 'fixed');
                    baro.css('top', '0');
                } else {
                    baro.css('position', '');
                    baro.css('top', '');
                }
            }
        );

        var selectedRange,
            options,
            toolbarBtnSelector,
            updateToolbar = function () {
                if (options.activeToolbarClass) {
                    $(options.toolbarSelector).find(toolbarBtnSelector).each(function () {
                        var command = $(this).data(options.commandRole);
                        if (document.queryCommandState(command)) {
                            $(this).addClass(options.activeToolbarClass);
                        } else {
                            $(this).removeClass(options.activeToolbarClass);
                        }
                    });
                }
            },
            execCommand = function (commandWithArgs, valueArg) {
                var commandArr = commandWithArgs.split(' '),
                    command = commandArr.shift(),
                    args = commandArr.join(' ') + (valueArg || '');
                document.execCommand(command, 0, args);
                updateToolbar();
            },
            bindHotkeys = function (hotKeys) {
                $.each(hotKeys, function (hotkey, command) {
                    editor.keydown(hotkey, function (e) {
                        if (editor.attr('contenteditable') && editor.is(':visible')) {
                            var ret=false;
                            if(typeof(command)=='string')
                            {
                                execCommand(command);
                            }else{
                                if(command['func']){
                                    var func=myfunc[command['func']];
                                    ret=func(command['data'],e);
                                    if(ret){

                                    }else{
                                        e.preventDefault();
                                        e.stopPropagation();
                                    }
                                }else{

                                }
                            }
                        }
                    }).keyup(hotkey, function (e) {
                        if (editor.attr('contenteditable') && editor.is(':visible')) {
                            var ret=false;
                            if(typeof(command)=='string')
                            {
                                execCommand(command);
                            }else{
                                if(command['keyupfunc']){
                                    var func=myfunc[command['keyupfunc']];
                                    ret=func(command['keyupdata'],e);
                                    if(ret){

                                    }else{
                                        e.preventDefault();
                                        e.stopPropagation();
                                    }
                                }else{

                                }
                            }
                        }
                    });
                });
            },
            getCurrentRange = function () {
                var sel = window.getSelection();
                if (sel.getRangeAt && sel.rangeCount) {
                    return sel.getRangeAt(0);
                }
            },
            saveSelection = function () {
                selectedRange = getCurrentRange();
            },
            restoreSelection = function () {
                var selection = window.getSelection();
                if (selectedRange) {
                    try {
                        selection.removeAllRanges();
                    } catch (ex) {
                        document.body.createTextRange().select();
                        document.selection.empty();
                    }

                    selection.addRange(selectedRange);
                }
            },
            insertFiles = function (files) {
                editor.focus();
                $.each(files, function (idx, fileInfo) {
                    if (/^image\//.test(fileInfo.type)) {
                        $.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {
                            execCommand('insertimage', dataUrl);
                        }).fail(function (e) {
                            options.fileUploadError("file-reader", e);
                        });
                    } else {
                        options.fileUploadError("unsupported-file-type", fileInfo.type);
                    }
                });
            },
            markSelection = function (input, color) {
                restoreSelection();
                if (document.queryCommandSupported('hiliteColor')) {
                    document.execCommand('hiliteColor', 0, color || 'transparent');
                }
                saveSelection();
                input.data(options.selectionMarker, color);
            },
            bindToolbar = function (toolbar, options) {

                //添加链接
                $('.add_link_btn').on('click',function(){
                    var thismodal=$(this).parents('.modal');
                    restoreSelection();
                    var add_link_link_obj=thismodal.find(".add_link_link:first");
                    var add_link_text_obj=thismodal.find(".add_link_text:first");

                    var link_add=add_link_link_obj.val();
                    var text_add=add_link_text_obj.val();


                    add_link_link_obj.on('focus',function () {
                        add_link_link_obj.parent().removeClass('has-error');
                    });

                    if(!link_add)
                    {
                        add_link_link_obj.parent().addClass('has-error');
                        return false;
                    }

                    if(link_add.indexOf('http://')!=0 && link_add.indexOf('https://')!=0 && link_add.indexOf('ftp://')!=0 )
                    {
                        link_add='http://'+link_add;
                    }
                    editor.focus();
                    if(!text_add)
                    {
                        text_add=link_add;
                    }
                    var str='<a href="'+link_add+'" target="_blank">'+text_add+'</a>';

                    // alert(str);
                    myfunc.insertHtml(str);

                    add_link_link_obj.val('');
                    add_link_text_obj.val('');

                    saveSelection();
                });
                //添加链接

                //添加图片
                $('._insert_img').on('click',function(){
                    if(options.upf_fact)
                    {
                        upf.init(options.upf_fact);
                    }
                    upf.clk(function(exid){
                        restoreSelection();
                        editor.focus();
                        var loading_img="<img src='/img/15upload.gif' id='imgloading"+exid+"'/>";
                        myfunc.insertHtml(loading_img);
                        saveSelection();
                    });
                    var str="";
                    upf.cusfunc=function(){
                        restoreSelection();
                        editor.focus();
                        var ret=upf.retdata;
                        if(ret.err && ret.err!=0)
                        {
                            alert(ret.emsg);
                            $("#imgloading"+ret.exinfo).remove();
                        }else{
                            str="<img style='max-width: 100%' src='"+ret.val+"' /><br/>";
                        }
                        $("#imgloading"+ret.exinfo).replaceWith(str);
                        saveSelection();
                    }
                });
                //添加图片

                //添加图片设置工具
                $(document).on('dblclick','.editor-zone img',function () {
                    $('#imgSet').modal('toggle');
                    $('#imgSet').find(".img_width:first").val($(this).attr('width'));
                    $(this).addClass('_now_set_img');
                });
                //添加链接
                $('.img_set_btn').on('click',function(){
                    var thismodal=$(this).parents('.modal');
                    restoreSelection();
                    var img_width_obj=thismodal.find(".img_width:first");

                    var img_width=img_width_obj.val();

                    var now_set_img=$('._now_set_img:first');

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    if(!$.trim(img_width))
                    {
                        return false;
                    }
                    now_set_img.attr('width',img_width);
                    saveSelection();
                });
                //添加链接
                //添加图片设置工具

                toolbar.find(toolbarBtnSelector).click(function () {
                    var thiscommand=$(this).data(options.commandRole);

                    if(thiscommand=='addlink'){
                        //点击添加链接
                        restoreSelection();
                        editor.focus();
                        var select_text=mygetSelectedContents();
                        var modelid=$(this).data('target');
                        $(modelid).find('.add_link_text:first').val(select_text);

                        saveSelection();
                    }else if(thiscommand.slice(0,3)=='_to'){
                        //设置标题
                        var hx=thiscommand.slice(4,7);
                        restoreSelection();
                        editor.focus();
                        var select_text=mygetSelectedContents();
                        select_text=$.trim($("<div>"+select_text+"</div>").text());//删除标签,取得文本。
                        if(select_text.length)
                        {
                            if(hx=='div')
                            {
                                select_text="<"+hx+">"+select_text+"</"+hx+">";
                            }else{
                                select_text="<"+hx+" class='_an'>"+select_text+"</"+hx+">";
                            }
                            myfunc.insertHtml(select_text);

                        }else{
                            document.execCommand('FormatBlock', 0, hx);
                            var sele = window.getSelection().focusNode.parentNode;

                            if(hx!='div')
                            {
                                $(sele).addClass('_an');
                            }
                        }
                        saveSelection();

                    }else if(thiscommand=='hr'){
                        restoreSelection();
                        editor.focus();
                        myfunc.insertHtml("<hr/>");
                        saveSelection();
                    }else{
                        restoreSelection();
                        editor.focus();
                        execCommand($(this).data(options.commandRole));
                        saveSelection();
                    }
                });
                toolbar.find('[data-toggle=dropdown]').click(restoreSelection);

                toolbar.find('input[type=text][data-' + options.commandRole + ']').on('webkitspeechchange change', function () {
                    var newValue = this.value;
                    /* ugly but prevents fake double-calls due to selection restoration */
                    this.value = '';
                    restoreSelection();
                    if (newValue) {
                        editor.focus();
                        execCommand($(this).data(options.commandRole), newValue);
                    }
                    saveSelection();
                }).on('focus', function () {
                    var input = $(this);
                    if (!input.data(options.selectionMarker)) {
                        markSelection(input, options.selectionColor);
                        input.focus();
                    }
                }).on('blur', function () {
                    var input = $(this);
                    if (input.data(options.selectionMarker)) {
                        markSelection(input, false);
                    }
                });
                toolbar.find('input[type=file][data-' + options.commandRole + ']').change(function () {
                    restoreSelection();
                    if (this.type === 'file' && this.files && this.files.length > 0) {
                        insertFiles(this.files);
                    }
                    saveSelection();
                    this.value = '';
                });
            },
            initFileDrops = function () {
                editor.on('dragenter dragover', false)
                    .on('drop', function (e) {
                        var dataTransfer = e.originalEvent.dataTransfer;
                        e.stopPropagation();
                        e.preventDefault();
                        if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
                            insertFiles(dataTransfer.files);
                        }
                    });
            };


        myfunc.initbar(options);



        toolbarBtnSelector = 'a[data-' + options.commandRole + '],button[data-' + options.commandRole + '],input[type=button][data-' + options.commandRole + ']';
        bindHotkeys(options.hotKeys);
        if (options.dragAndDropImages) {
            initFileDrops();
        }
        bindToolbar($(options.toolbarSelector), options);
        editor.attr('contenteditable', true)
            .on('mouseup keyup mouseout', function () {
                saveSelection();
                updateToolbar();
            });
        $(window).bind('touchend', function (e) {
            var isInside = (editor.is(e.target) || editor.has(e.target).length > 0),
                currentRange = getCurrentRange(),
                clear = currentRange && (currentRange.startContainer === currentRange.endContainer && currentRange.startOffset === currentRange.endOffset);
            if (!clear || isInside) {
                saveSelection();
                updateToolbar();
            }
        });
        return this;
    };
    $.fn.wysiwyg.defaults = {
        hotKeys: {
            'ctrl+b meta+b': 'bold',
            'ctrl+i meta+i': 'italic',
            'ctrl+u meta+u': 'underline',
            'ctrl+z meta+z': 'undo',
            'ctrl+y meta+y meta+shift+z': 'redo',
            'ctrl+l meta+l': 'justifyleft',
            'ctrl+r meta+r': 'justifyright',
            'ctrl+e meta+e': 'justifycenter',
            'ctrl+j meta+j': 'justifyfull',
            'shift+tab': 'outdent',
            'tab': {'func': "insertHtml", "data": "&nbsp;&nbsp;&nbsp;&nbsp;"},
            'return':{'func': "enterdown", "data": "<br/>",'keyupfunc':'enterup',},
            'backspace':{'keyupfunc':'taghandle'},
        },
        toolbarSelector: '[data-role=editor-toolbar]',
        commandRole: 'edit',
        activeToolbarClass: 'btn-info',
        selectionMarker: 'edit-focus-marker',
        selectionColor: 'darkgrey',
        dragAndDropImages: true,
        fileUploadError: function (reason, detail) {
            console.log("File upload error", reason, detail);
        }
    };
}(window.jQuery));

function mygetSelectedContents() {
    if (window.getSelection && window.getSelection().rangeCount) { //chrome,firefox,opera
        var range = window.getSelection().getRangeAt(0);
        var container = document.createElement('div');
        container.appendChild(range.cloneContents());
        return container.innerHTML;
        //return window.getSelection(); //只复制文本
    }
    else if (document.getSelection && window.getSelection().rangeCount) { //其他
        var range = window.getSelection().getRangeAt(0);
        var container = document.createElement('div');
        container.appendChild(range.cloneContents());
        return container.innerHTML;
        //return document.getSelection(); //只复制文本
    }
    else if (document.selection) { //IE特有的
        return document.selection.createRange().htmlText;
        //return document.selection.createRange().text; //只复制文本
    }
    return false;
}

$(function(){
    function initToolbarBootstrapBindings() {
        var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
                'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
                'Times New Roman', 'Verdana'],
            fontTarget = $('[title=Font]').siblings('.dropdown-menu');
        $.each(fonts, function (idx, fontName) {
            fontTarget.append($('<li><a data-edit="fontName ' + fontName + '" style="font-family:\'' + fontName + '\'">' + fontName + '</a></li>'));
        });
        $('a[title]').tooltip({container: 'body'});
        $('.dropdown-menu input').click(function () {
                return false;
            })
            .change(function () {
                $(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle');
            })
            .keydown('esc', function () {
                this.value = '';
                $(this).change();
            });

        $('[data-role=magic-overlay]').each(function () {
            var overlay = $(this), target = $(overlay.data('target'));
            overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight());
        });
        if ("onwebkitspeechchange" in document.createElement("input")) {
            var editorOffset = $('#editor').offset();
            $('#voiceBtn').css('position', 'absolute').offset({
                top: editorOffset.top,
                left: editorOffset.left + $('#editor').innerWidth() - 35
            });
        } else {
            $('#voiceBtn').hide();
        }
    };



    function showErrorAlert(reason, detail) {
        var msg = '';
        if (reason === 'unsupported-file-type') {
            msg = "Unsupported format " + detail;
        }
        else {
            console.log("error uploading file", reason, detail);
        }
        $('<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>' +
            '<strong>File upload error</strong> ' + msg + ' </div>').prependTo('#alerts');
    };
    initToolbarBootstrapBindings();
});